<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Article;
use App\Http\Model\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    //get  admin/article   全部分类列表
    public function index(){
        
        $article_datas = Article::orderBy('art_id','desc')->paginate(6);
        return view('admin.article.index',compact('article_datas'));
    }



    //post  admin/article  获取要添加的数据并存储到数据库
    public function store(){
        //验证
        $input = Input::except("_token");
        $rules = [
            'art_title'=>'required',//定义规则，规则都是框架自带的
            'art_content'=>'required'
        ];
        //提示信息
        $message = [
            'art_title.required'=>'文章标题不能为空',
            'art_content.required'=>'文章内容不能为空'
        ];
        //创建验证对象，哪些post值，规则是什么，提示什么

        $validator = Validator::make($input,$rules,$message);
        //如果通过验证，
        if($validator->passes()){
            $input['art_time'] = time();
            $re = Article::create($input);
            if($re){
                return redirect('admin/article');
            }else{
                return back()->with('errors','数据填入失败');
            }


        }else{

            return back()->withErrors($validator);
        }
    }

    //get. admin/article/create   添加页面的显示及数据分配
    public function create(){
        $cate_datas = (new Category())->tree();
        
        return view('admin.article.add',compact('cate_datas'));
    }



    //put admin/article/{article}
    public function update($art_id){
        $input = Input::except('_token','_method');
        $re = Article::where('art_id',$art_id)->update($input);
        if($re){
            return redirect('admin/article');
        }else{
            return back()->with('msg',"数据更新失败");
        }
    }

    //get admin/article/{article}/edit  显示编辑页面并数据分配
    public function edit($art_id){
        $cate_datas = (new Category())->tree();
        $article_data = Article::find($art_id);
        return view('admin.article.edit',compact('cate_datas','article_data'));
    }

    //get admin/category/{category}
    public function show(){

    }

    //delete admin/category/{category}
    public function destroy($art_id){
        $re = Article::where("art_id",$art_id)->delete();

        if($re){
            $data = [
                'status'=>1,
                'msg'=>"文章删除成功！"
            ];
        }else{
            $data = [
                'status'=>0,
                'msg'=>"文章删除失败"
            ];
        }
        return $data;
    }



}
